/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package aso.upna.threads;

import aso.upna.config.ClientConfig;
import aso.upna.information.StreamInfo;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JProgressBar;

/**
 *
 * @author triki
 */

/*
 * Esta clase es la que se utilizará para conectarse al otro cliente. Cuando
 * su negociacion termine. Esta clase abrirá el hilo UDP para esperar
 * la recepción del flujo (cancion) por parte del otro cliente.
 *
 * La conexion que entablará este hilo es una conexion entre clientes.

 */

public class ClientConnect implements Runnable {

    private ClientConfig conf;
    private int remoteTcpPort;
    private String ip;
    private String toPlay;

    private JProgressBar progress;
    
    public ClientConnect(ClientConfig cfg,String ip,int remoteTCPport,String toPlay)
    {
        conf = cfg;
        this.ip = ip;
        remoteTcpPort = remoteTCPport;
        this.toPlay = toPlay;
        progress = null;
    }

    public ClientConnect(ClientConfig cfg,JProgressBar progress,String ip,int remoteTCPport,String toPlay)
    {
        conf = cfg;
        this.ip = ip;
        remoteTcpPort = remoteTCPport;
        this.toPlay = toPlay;
        this.progress = progress;
    }

    public void registerObserver(JProgressBar prog)
    {
        progress = prog;
    }

    public void run() {

        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        String req = null;
        String rep = null;
        Object aux = null;
        StreamInfo inf;
        
        UdpStream uStream = new UdpStream(conf);
        Thread udpThread = new Thread(uStream);

        try {
            
            Socket sock = new Socket(ip, remoteTcpPort);

            oos = new ObjectOutputStream(sock.getOutputStream());
            ois = new ObjectInputStream(sock.getInputStream());

            req = new String("Play "+toPlay+" "+conf.getUdpPort()+" ");
            udpThread.start();

            oos.writeObject(req);

            while(true)
            {
                try
                {
                    aux = ois.readObject();

                    if(aux instanceof String)
                    {
                        rep = (String) aux;
                        if(rep.startsWith("OK"))
                            break;
                    }
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                }
            }

            String[] parts = rep.split(" ");
            int p_total = Integer.parseInt(parts[1]);
            inf = new StreamInfo(p_total);
            uStream.registerStreamInfo(inf);

            int per = 0;
            
            while(per < 100)
            {
                per = inf.getPercetCompleted();
  
                if(progress != null)
                {
                    progress.setValue(per);
                    progress.setString(""+per+"%");
                }
                else
                {
                    System.out.println("Porcentaje: "+per);
                }

                try
                {
                    Thread.sleep(1000);
                }
                catch (InterruptedException ex)
                {
                    Logger.getLogger(ClientConnect.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            try {
                udpThread.join();
                System.out.println("HILO UDP Terminado");
            } catch (InterruptedException ex) {
                Logger.getLogger(ClientConnect.class.getName()).log(Level.SEVERE, null, ex);
            }
           
           
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }    
    }

}
